package com.yunmai.library.db;

import android.content.Context;
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.dao.ObjectCache;
import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.table.TableInfo;
import java.sql.SQLException;

/**
 * 默认解析器，使用ormlite自带解析
 *
 * @author liyi
 * create at 2018/3/26
 **/
public class SimpleResultParse<T> implements ResultParse {
  private TableInfo<T, ?> tableInfo = null;

  private Context mContext;

  public SimpleResultParse(Context context) {
    this.mContext = context;
  }

  private void checkTableInfo(Class<?> clazz) throws SQLException {
    if (tableInfo != null) return;
    tableInfo =
        new TableInfo<T, Object>(DBOpenHelper.getInstance(mContext).getConnectionSource(),
            (BaseDaoImpl<T, Object>) DBOpenHelper.getInstance(mContext).getDao(clazz),
            (Class<T>) clazz);
  }

  @Override
  public <T> T parseResult(Class<?> clazz, String[] columnNames, String[] resultColumns)
      throws SQLException {
    checkTableInfo(clazz);
    T rowObj = (T) this.tableInfo.createObject();

    for (int i = 0; i < columnNames.length; ++i) {
      if (i < resultColumns.length) {
        FieldType fieldType = this.tableInfo.getFieldTypeByColumnName(columnNames[i]);
        Object fieldObj = fieldType.convertStringToJavaField(resultColumns[i], i);
        if(fieldObj != null) {
          fieldType.assignField(rowObj, fieldObj, false, (ObjectCache) null);
        }
      }
    }
    return rowObj;
  }
}
